<template>
	<view class="fix-top-window">
		<view class="uni-header">
			{{appname}} （{{appid}}）

			<view class="uni-group">
				<button type="primary" size="mini" @click="showModalLogs">同步日志</button>
			</view>
		</view>
		<view class="uni-container">
			<view class="uni-ad-admin-tips" v-if="syncRevenueStatus">
				昨日广告收益数据同步已完成
			</view>
			<view class="uni-ad-admin-tips" v-if="!syncRevenueStatus">
				昨日广告收益数据同步未完成
			</view>

			<view class="uni-ad-admin--x p-1015">
				<view class="flex flex-pull">
					<uni-ad-admin-tabs label="日期选择" :current="currentDateTab" mode="date" @change="changeTimeRange" />
					<uni-datetime-picker type="daterange" :end="new Date().getTime()" v-model="start_time"
						returnType="timestamp" :clearIcon="false" class="uni-stat-datetime-picker"
						:class="{'uni-stat__actived': currentDateTab < 0 && !!start_time.length}"
						@change="useDatetimePicker" />
				</view>
			</view>

			<uni-ad-admin-panel :items="panelData" unit="美元"></uni-ad-admin-panel>

			<view class="uni-ad-admin--x flex p-1015">
				<view class="uni-ad-admin-card-header">
					趋势分析（结算币种：美元）
				</view>
				<view class="uni-charts-box">
					<qiun-data-charts type="area" :chartData="chartData" :eopts="eopts" echartsH5 echartsApp
						tooltipFormat="tooltipCustom" :errorMessage="errorMessage" />
				</view>
			</view>


			<uni-ad-detail-table ref="detailTable" unit="美元"></uni-ad-detail-table>
		</view>

		<uni-ad-sync-logs ref="uniadSyncLogs" :ad_region="where.ad_region" :appid="appid"></uni-ad-sync-logs>
	</view>
</template>

<script>
	import {
		summaryMap,
		platformMap
	} from './fieldsMap.js'
	import timeUtil from '@/uni_modules/uni-ad-admin/js_sdk/timeUtil'
	import {
		eopts,
		format,
		getTimeOfSomeDayAgo,
	} from '@/uni_modules/uni-ad-admin/js_sdk/util'

	const db = uniCloud.database()
	const dbCmd = db.command
	const $ = dbCmd.aggregate
	const ADREGION = 2
	export default {
		data() {
			return {
				appid: '',
				appname: '',
				panelData: summaryMap,
				tableName: 'uni-ad-adp-revenues',
				appTableName: 'uni-ad-app-revenues',
				where: {
					ad_region: ADREGION,
					revenue_date: timeUtil.yestoday()
				},
				syncRevenueStatus: false,
				currentDateTab: 0,
				platformTab: 1,
				platformMap,
				start_time: [],
				eopts,
				chartData: {},
				errorMessage: "",
			}
		},
		onLoad(e) {
			if (typeof(e) != 'undefined') {
				this.appid = e.appid
				this.getAppInfo()
				this.getSyncRevenueStatus()
				this.getSummaryData()
			}
		},
		methods: {
			getAppInfo() {
				db.collection('opendb-app-list')
					.where({
						appid: this.appid
					})
					.get()
					.then(res => {
						let {
							data
						} = res.result
						console.log('data', res)
						if (data.length) {
							this.appname = data[0].name
						}
					})
			},
			showModalLogs() {
				this.$refs.uniadSyncLogs.open()
			},
			useDatetimePicker() {
				this.currentDateTab = null
				this.getChartData()
				this.getTableData()
			},
			changeTimeRange(id, index) {
				this.currentDateTab = index
				const day = 24 * 60 * 60 * 1000
				let start, end
				start = getTimeOfSomeDayAgo(id)
				if (!id) {
					end = getTimeOfSomeDayAgo(0) + day - 1
				} else {
					end = getTimeOfSomeDayAgo(0) - 1
				}
				this.start_time = [start, end]
				this.getChartData()
				this.getTableData()
			},
			getSyncRevenueStatus() {
				db.collection('uni-ad-sync-logs').where({
						sync_date: timeUtil.yestoday(),
						appid: this.appid,
						ad_region: ADREGION
					})
					.get()
					.then(res => {
						let {
							data
						} = res.result

						if (data && data.length > 0) {
							this.syncRevenueStatus = data[0].status === 1
						}
					})
			},
			async getSummaryData() {
				let yestodaySummary = 0,
					sevenSummary = 0,
					monthSummary = 0,
					lastMonthSummary = 0

				let yestoday = timeUtil.yestoday()
				let weekday = timeUtil.plusDay(-7)
				let first = timeUtil.getMonthStart()
				let last_month_end = timeUtil.plusDay(-1, 'yyyyMMdd', first)
				let last_month_start = timeUtil.getMonthStart(timeUtil.toTime(last_month_end))
				let dates = [
					[yestoday, yestoday],
					[weekday, yestoday],
					[first, yestoday],
					[last_month_start, last_month_end]
				]

				for (let i in dates) {
					let where = {
						appid: this.appid,
						ad_region: ADREGION,
						revenue_date: dbCmd.and(
							dbCmd.gte(dates[i][0]),
							dbCmd.lte(dates[i][1])
						)
					}

					let revenues = await db.collection(this.appTableName)
						.aggregate()
						.match(where)
						.group({
							_id: null,
							revenue: $.sum('$revenue')
						})
						.end()
					let {
						data
					} = revenues.result

					let revenue = data.length > 0 ? data[0].revenue || 0 : 0
					this.panelData[i].value = format(revenue / 1000)
				}
			},
			getTableData() {
				this.$refs.detailTable.start({
					appid: this.appid,
					ad_platform: this.platformTab,
					start_time: this.start_time[0],
					end_time: this.start_time[1],
					ad_region: ADREGION,
					search: {
						platformSelectValue: 1,
						adTypeSelectValue: 0,
						systemSelectValue: '',
						positionSelectValue: '',
						mpAdTypeSelectValue: 0
					}
				})
			},
			async getChartData() {
				let start = this.start_time[0]
				let end = this.start_time[1]

				let name = '预估收益'
				const options = {
					categories: [],
					series: [{
						name,
						label: {
							show: false
						},
						data: []
					}]
				}

				let revenus = await this.getChartRevenue(start, end)

				for (let i = start; i <= end; i += 86400000) {
					let cd = timeUtil.timeFormat(i, 'yyyyMMdd')

					options.categories.push(timeUtil.dateFormat(cd))
					let find = revenus.result.data.find((item) => {
						return item.revenue_date == cd;
					})

					let revenue = find ? find.revenue : 0
					options.series[0].data.push((revenue / 1000).toFixed(3))
				}

				this.chartData = options
			},
			async getChartRevenue(start, end) {
				let startDate = timeUtil.timeFormat(start, 'yyyyMMdd')
				let endDate = timeUtil.timeFormat(end, 'yyyyMMdd')

				let where = {
					appid: this.appid,
					ad_region: ADREGION,
					revenue_date: dbCmd.and(
						dbCmd.gte(startDate),
						dbCmd.lte(endDate)
					)
				}
				where.ad_platform = 2

				return await db.collection(this.tableName)
					.where(where)
					.groupBy('revenue_date')
					.groupField('sum(revenue) as revenue')
					.orderBy('revenue_date desc')
					.get()
			}
		}
	}
</script>

<style lang="scss">
	@import "@/uni_modules/uni-ad-admin/common/uni-ad-admin.scss";

	.uni-ad-platform-tab {
		flex: 1;
		justify-content: flex-end;

		&--item {
			cursor: pointer;
			font-size: 14px;
			padding: 4px 10px;
		}

		.active {
			border-bottom: 2px $uni-color-primary solid;
		}
	}
</style>